package com.ocom.payhandle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.common.HttpUtils;
import com.ocom.common.entity.card.EntiyXfMerchPayInfo;
import com.ocom.common.entity.typehandler.EntityCcbBusinessInfo;
import com.ocom.common.entity.typehandler.EntityCcbPosInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payhandle.dao.IDaoCcbBusinessInfo;
import com.ocom.payhandle.service.CcbBusinessInfoService;
import com.ocom.payhandle.service.CcbPosInfoService;
import com.ocom.payhandle.service.CompanyInfoService;
import com.ocom.payhandle.service.XfMerchPayInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * <p>
 * 智慧生活商家信息 服务实现类
 * </p>
 *
 * @author js
 * @since 2023-10-04
 */
@Slf4j
@Service
public class CcbBusinessInfoServiceImpl extends ServiceImpl<IDaoCcbBusinessInfo, EntityCcbBusinessInfo> implements CcbBusinessInfoService {
//    @Value("${pay.url}")
//    private String payUrl;
    @Resource
    private XfMerchPayInfoService xfMerchPayInfoService;
    @Resource
    private CcbPosInfoService ccbPosInfoService;
    @Resource
    private IDaoCcbBusinessInfo iDaoCcbBusinessInfo;
    @Autowired
    private CompanyInfoService companyInfoService;

    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.MASTER)
    public Result newBusiness(Long comId,EntityCcbBusinessInfo request){
        if(request.getMerchId()==null || StringUtils.isEmpty(request.getBusinessName() )  || StringUtils.isEmpty(request.getMrchId()) || StringUtils.isEmpty(request.getBranchId()) || StringUtils.isEmpty(request.getMobile()) ) {
            return new Result(501,"必填参数不能为空.",null);
        }
        QueryWrapper<EntityCcbBusinessInfo> query = Wrappers.query();
        if(request.getMerchId() == 0){
            query.select("merch_id as merchId , business_name as businessName");
            query.eq("com_id",comId);
            query.last("limit 1");
            EntityCcbBusinessInfo info = this.getOne(query);
            if(info != null){
                return new Result(501,"已有商户绑定商家："+info.getBusinessName(),null);
            }
        }else if(request.getMerchId() >0 ){
            EntityCcbBusinessInfo ccbBusinessInfo = iDaoCcbBusinessInfo.checkMerchInfo(request.getComId(),request.getMerchId());
            if(ccbBusinessInfo != null){
                return new Result(501,"已绑定商家："+ccbBusinessInfo.getBusinessName(),null);
            }
        }
        query.eq("com_id",request.getComId()).and(wrapper -> wrapper.eq("business_name",request.getBusinessName()).or().eq("mrch_id",request.getMrchId()));
        query.last("limit 1");
        EntityCcbBusinessInfo info = this.getOne(query);
        if(info != null){
            return new Result(501,"商家名称或商户号已存在。",null);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("businessName", request.getBusinessName());
        map.put("mrchId", request.getMrchId());
        map.put("BRANCH_ID", request.getBranchId());
        map.put("posAmount", 0);
        map.put("MOBILE", request.getMobile());
//        map.put("posIds", );
        Result payInfo = setPayInfo(request, "/ccb/merchant/creation.do", map, request.getMerchId(),1);
        return payInfo;
    }

    public Result updateBusiness(EntityCcbBusinessInfo request){
        HashMap<String, Object> map = new HashMap<>();
        map.put("businessId", request.getBusinessId());
        map.put("businessName", request.getBusinessName());
        map.put("posAmount", request.getPosAmount());
        map.put("mobile", request.getMobile());
        map.put("posIds", request.getPosIds());
        map.put("status", request.getStatus());
        Result payInfo = setPayInfo(request, "/ccb/merchant/update.do", map, null,2);
        return payInfo;
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB,companyId = "comId")
    private Result setPayInfo(EntityCcbBusinessInfo request,String payUrlSuffix,HashMap<String, Object> map, Long merchId, Integer updateOrSave){
        EntiyXfMerchPayInfo entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(request.getComId(), merchId);
        if (null == entiyXfMerchPayInfo  || entiyXfMerchPayInfo.equals("null")) {
           return ResultUtil.error(ResultEnum.Err_2031);
        }
        if(entiyXfMerchPayInfo.getCompanyId() == null){
            return new Result(501, " 该单位编号company_id为空.", null);
        }
        map.put("companyId", entiyXfMerchPayInfo.getCompanyId());
        map.put("userName", entiyXfMerchPayInfo.getUserName());
        map.put("payPassword", entiyXfMerchPayInfo.getPassword());
        log.info(payUrlSuffix + "统一支付接口发送内容: {}", map);
        String payUrl = companyInfoService.getPayCenterUrl(request.getComId(), entiyXfMerchPayInfo.getCompanyId());
        String sJson = HttpUtils.postJson(payUrl + payUrlSuffix, map);
        if(sJson == null || sJson.equals("")){
            return new Result(500, payUrlSuffix + " 统一支付接口无相应.", null);
        }
        log.info(payUrlSuffix + "统一支付接口相应内容: {}", sJson);
        JSONObject results = JSON.parseObject(sJson);
        if (results.getInteger("code") != 200) {
            return new Result(results.getInteger("code"), results.getString("msg"), null);
        }
        JSONArray jsonArrayData = results.getJSONArray("data");
        JSONObject jsonObjectDate = jsonArrayData.getJSONObject(0);
        String businessId = jsonObjectDate.getString("BUSINESS_ID");
        JSONArray jsonPosInfo = jsonObjectDate.getJSONArray("POS_INFO");
        request.setBusinessId(businessId);
//        request.setCreateTime(LocalDateTime.now());
//        request.setUpdateTime(LocalDateTime.now());
        boolean bOperate;
        UpdateWrapper<EntityCcbBusinessInfo> updateWrapper = Wrappers.update();
        updateWrapper.eq("business_id",businessId);
        updateWrapper.eq("com_id",request.getComId());
//        updateWrapper.eq("merch_id",request.getMerchId());
        bOperate = false;
        if(updateOrSave == 1){
            bOperate = this.save(request);
        }else if(updateOrSave == 2){
            bOperate = this.update(request,updateWrapper);
        }

        if(bOperate){
            if(jsonPosInfo != null && jsonPosInfo.size()>0){
                UpdateWrapper<EntityCcbPosInfo> update = Wrappers.update();
                for(int i=0;i < jsonPosInfo.size();i++ ){
                    update.eq("business_id",request.getBusinessId());
                    update.eq("pos_id",jsonPosInfo.getJSONObject(i).getString("POS_ID"));
                    update.eq("vpos_id",jsonPosInfo.getJSONObject(i).getString("VPOS_ID"));
                    EntityCcbPosInfo posInfo = new EntityCcbPosInfo();
                    posInfo.setComId(request.getComId());
                    posInfo.setBindMerchId(request.getMerchId());
                    posInfo.setPosId(jsonPosInfo.getJSONObject(i).getString("POS_ID"));
                    posInfo.setVposId(jsonPosInfo.getJSONObject(i).getString("VPOS_ID"));
//                  posInfo.setBusinessId(resultsMsg.getString("BUSINESS_ID"));
                    posInfo.setBusinessId(request.getBusinessId());
                    ccbPosInfoService.saveOrUpdate(posInfo,update);
                    update.clear();
                }
            }
        }
        return ResultUtil.success(bOperate);
    }
}
